#!/usr/bin/env python
# coding=utf-8

# File Name: recieve.py
# Author: Bill Zhang
# Mail: zchcandid@gmail.com 
# Created Time: Fri 29 Nov 2013 03:08:41 PM CST
import pika
from libUpdate import UpdateClass
import simplejson as json
#import pymongo
import libPushData as push
import time
#mysql connector

def callback(ch, method, properties, body):
    """This is callback function:
    Some conversion is as follows:
        UC=UpdateClass
        IU=ID and URL
        QP=quantity and price
    The wrong code:
        if can not read the html code: "Q":-1
        if can not parse the html code: "Q1":-1
    
    """
    print(".......开始时间:%s..........." % time.ctime())
    body=body.decode('utf-8')
    IU=json.loads(body)
    URL=IU["URL"]
    k=IU["k"]
    ID =IU["ID"]
    print(URL)
    #ch.basic_ack(delivery_tag = method.delivery_tag)
    #return 
    UC=UpdateClass()
    if UC is 'W':
        print("Something wrong detected when init the UpdateClass")
        log=open("log/update.log","a")
        log.write("Something wrong detected when init the UpdateClass")
        log.close()
        ch.basic_ack(delivery_tag = method.delivery_tag)
        return 
    #when run success HtmlCode will be (0,0)
    PI=UC.toGetData(URL,ID,k)
    if PI==0:
        PI={"ID":ID, "OnHand":0, "Items": [{}]} 
    #push the data API
    print(".........采集结束时间:%s,用时:%s秒......." % (time.ctime(),time.process_time()))
    print(PI)
    check=push.pushing(PI,k)
    if check is 101:
        push.pushing(PI,k)
    print(".........推送结束时间:%s,用时:%s秒......." % (time.ctime(),time.process_time()))
    ch.basic_ack(delivery_tag = method.delivery_tag)
def recieve():
    print("Icmal collection center has been runing!")
    connection = pika.BlockingConnection(pika.ConnectionParameters( host = '192.168.100.204' ))
    channel = connection.channel()
    channel.queue_declare(queue = 'icmall' , durable = True )
    channel.basic_qos(prefetch_count = 1 )
    channel.basic_consume(callback,queue = 'icmall')
    channel.start_consuming()
#debug mode
if __name__=="__main__":
    """
    ---if __name=="__main__"-----
    This is for debug this moudle,
    When run this moudle as the main 
    the code below will run
    """
   # i=db.update.find()
   # print(list(i))
    a='{"ID":1,"URL":"www.baidu.com"}'
    b=json.loads(a)
    print(b)
    print(b["ID"])
